package com.fjd.task;

import com.fjd.constant.MessageConstant;
import com.fjd.context.BaseContext;
import com.fjd.entity.SalesOrder;
import com.fjd.mapper.SalesOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class SaleTask {
    @Autowired
    private SalesOrderMapper salesOrderMapper;

    /**
     * 超时订单处理
     */
    //这里暂定每三分钟处理一次
    @Scheduled(cron = "0 0/3 * * * ?") //每3分钟执行一次
    public void cancelTimeOutOrder(){
        //log.info("定时任务启动，处理超时订单");
        LocalDateTime time = LocalDateTime.now().plusDays(-1);//一天前（24小时不付款自动取消）
        //LocalDateTime time = LocalDateTime.now().plusSeconds(-20);//测试20秒前
        List<SalesOrder> list = salesOrderMapper.getByStatusAndTime(SalesOrder.PENDING_PAYMENT,time);
        if (list != null && list.size() > 0){
            for (SalesOrder salesOrder : list) {
                //取消订单
                salesOrder.setOrderStatus(SalesOrder.CANCELLED);
                //这个取消原因应该放在哪里？我先放备注吧
                //取消原因后面也总结一个常量类
                salesOrder.setNote(MessageConstant.ORDER_STATUS_TIMEOUT);
                salesOrder.setLastModifiedBy("system"); //说明是系统取消修改的
                salesOrder.setLastModifiedDate(LocalDateTime.now());
                salesOrderMapper.update(salesOrder);
            }
        }
    }
}
